package com.springcloud.commom.config;

import com.springcloud.commom.api.R;
import com.springcloud.commom.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常处理器
 */
@RestControllerAdvice
public class AdviceConfig {
    private Logger logger = LoggerFactory.getLogger(AdviceConfig.class);

    /**
     * 全局捕获异常类，只作用在@RequestMapping注解上 针对所有异常进行处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public R errorHandler(Exception ex) {
        ex.printStackTrace();
        logger.error(ex.getMessage());

        String msg = "服务器内部错误!";
        if (ex instanceof BindException) {
            BindException exs = (BindException) ex;
            msg = exs.getBindingResult().getFieldError().getDefaultMessage();
        }

        if (ex instanceof HttpRequestMethodNotSupportedException) {
            HttpRequestMethodNotSupportedException exs = (HttpRequestMethodNotSupportedException) ex;

            msg = exs.getMessage();
        }

        if(ex instanceof HttpMessageNotReadableException){
            msg = "需要传递json格式参数";
        }

        if(ex instanceof ConstraintViolationException){
            ConstraintViolationException exs = (ConstraintViolationException) ex;

            msg = exs.getMessage();
        }

      return R.fail(msg);
    }

    @ResponseBody
    @ExceptionHandler(value = ServiceException.class)
    public R errorHandler(ServiceException ex) {
        return R.fail(ex.getResultCode().getCode(),ex.getMessage());
    }

}
